package com.quan.api.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.quan.api.cart.service.CartService;
import com.quan.api.cart.vo.CartItemVo;
import com.quan.api.cart.vo.CartVo;
import com.quan.commons.core.exception.BizException;
import com.quan.mall.entity.PmsSku;
import com.quan.mall.service.PmsSkuService;
import com.quan.mall.service.PmsSpuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


/**
 * 购物车
 */
@Slf4j
@Service("cartService")
public class CartServiceImpl implements CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PmsSpuService pmsSpuService;

    @Autowired
    private PmsSkuService pmsSkuService;

    @Autowired
    private ThreadPoolExecutor executor;

    public final static String CART_PREFIX = "mall:cart:";

    @Override
    public CartItemVo addToCart(Long memberId, Long skuId, Integer num) throws ExecutionException, InterruptedException {

        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);

        //判断Redis是否有该商品的信息
        String productRedisValue = (String) cartOps.get(skuId.toString());
        //如果没有就添加数据
        if (StringUtils.isEmpty(productRedisValue)) {

            //2、添加新的商品到购物车(redis)
            CartItemVo cartItemVo = new CartItemVo();
            //开启第一个异步任务
            CompletableFuture<Void> getSkuInfoFuture = CompletableFuture.runAsync(() -> {
                //1、查询当前要添加商品的信息
                final PmsSku sku = this.pmsSkuService.getById(skuId);
                //数据赋值操作
                cartItemVo.setSkuId(sku.getId());
                cartItemVo.setTitle(sku.getSkuName());
                cartItemVo.setImage(sku.getSkuImg());
                cartItemVo.setPrice(sku.getSalePrice());
                cartItemVo.setSkuAttrValues(sku.getDescar());
                cartItemVo.setCount(num);
            }, executor);

            //等待所有的异步任务全部完成
            CompletableFuture.allOf(getSkuInfoFuture).get();

            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        } else {
            //购物车有此商品，修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue, CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount() + num);
            //修改redis的数据
            String cartItemJson = JSON.toJSONString(cartItemVo);
            cartOps.put(skuId.toString(), cartItemJson);

            return cartItemVo;
        }
    }

    @Override
    public CartItemVo getCartItem(Long memberId, Long skuId) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);

        String redisValue = (String) cartOps.get(skuId.toString());

        CartItemVo cartItemVo = JSON.parseObject(redisValue, CartItemVo.class);

        return cartItemVo;
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartVo getCart(Long memberId) throws ExecutionException, InterruptedException {
        String cartKey = CART_PREFIX + memberId;

        CartVo cartVo = new CartVo();
        List<CartItemVo> cartItems = getCartItems(cartKey);
        cartVo.setItems(cartItems);

        return cartVo;
    }

    /**
     * 获取到我们要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps(Long memberId) {

        String cartKey = CART_PREFIX + memberId;

        //绑定指定的key操作Redis
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);

        return operations;
    }


    /**
     * 获取购物车里面的数据
     * @param cartKey
     * @return
     */
    private List<CartItemVo> getCartItems(String cartKey) {
        //获取购物车里面的所有商品
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> cartItemVoStream = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItemVo cartItem = JSON.parseObject(str, CartItemVo.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItemVoStream;
        }
        return null;

    }


    @Override
    public void clearCartInfo(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long memberId, Long skuId, Boolean checked) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(memberId, skuId);
        //修改商品状态
        cartItem.setCheck(checked);

        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        cartOps.put(skuId.toString(), redisValue);
    }

    @Override
    public void checkItemAll(Long memberId, Boolean checked) {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        final List<Object> values = cartOps.values();


        for (Object value : values) {
            String redisVal = (String) value;

            CartItemVo cartItem = JSON.parseObject(redisVal, CartItemVo.class);
            cartItem.setCheck(!checked);

            //序列化存入redis中
            String redisValue = JSON.toJSONString(cartItem);

            BoundHashOperations<String, Object, Object> cart = getCartOps(memberId);
            cart.put(cartItem.getSkuId().toString(), redisValue);
        }
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long memberId, Long skuId, Integer num) {
        //查询购物车里面的商品
        CartItemVo cartItem = getCartItem(memberId, skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        //序列化存入redis中
        String redisValue = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), redisValue);
    }


    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteIdCartInfo(Long memberId, Long skuId) {

        BoundHashOperations<String, Object, Object> cartOps = getCartOps(memberId);
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItemVo> getUserCartItems(Long memberId) {

        List<CartItemVo> cartItemVoList = new ArrayList<>();
        //获取购物车项
        String cartKey = CART_PREFIX + memberId;
        //获取所有的
        List<CartItemVo> cartItems = getCartItems(cartKey);
        if (cartItems == null) {
            throw new BizException("购物车为空");
        }
        //筛选出选中的
        cartItemVoList = cartItems.stream()
                .filter(items -> items.getCheck())
                .map(item -> {
                    //更新为最新的价格（查询数据库）
                    BigDecimal price = this.pmsSkuService.getPrice(item.getSkuId());
                    item.setPrice(price);
                    return item;
                })
                .collect(Collectors.toList());

        return cartItemVoList;
    }
}
